﻿using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using ZXing;
using ZXing.Common;
using ZXing.QrCode;

namespace Common
{
    public class BarCode
    {
        /// <summary>
        /// 生成条形码
        /// </summary>
        /// <param name="picBox1"></param>
        /// <param name="Content"></param>
        public void CreateBarCode(PictureBox picBox1, string Content)
        {
            Regex rg = new Regex("^[0-9]{12}$");
            if (!rg.IsMatch(Content))
            {
                MessageBox.Show("本例采用EAN_13编码，请输入12位数字");
                return;
            }

            EncodingOptions options = null;
            BarcodeWriter writer = null;
            options = new EncodingOptions
            {
                Width = picBox1.Width,
                Height = picBox1.Height
            };
            writer = new BarcodeWriter();
            writer.Format = BarcodeFormat.ITF;
            writer.Options = options;

            Bitmap bitmap = writer.Write(Content);
            picBox1.Image = bitmap;
        }

        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="picBox1"></param>
        /// <param name="Content"></param>
        public void CreateQuickMark(PictureBox picBox1, string Content)
        {
            if (string.IsNullOrEmpty(Content))
            {
                MessageBox.Show("输入内容不能为空");
                return;
            }

            EncodingOptions options = null;
            BarcodeWriter writer = null;
            options = new QrCodeEncodingOptions
            {
                DisableECI = true,
                CharacterSet = "UTF-8",
                Width = picBox1.Width,
                Height = picBox1.Height
            };
            writer = new BarcodeWriter();
            writer.Format = BarcodeFormat.QR_CODE;
            writer.Options = options;
            Bitmap bitmap = writer.Write(Content);
            picBox1.Image = bitmap;
        }

        ///<summary>
        ///解码
        ///</summary>
        ///<paramname="pictureBox1"></param>
        public void Decode(PictureBox picBox1)
        {
            BarcodeReader reader = new BarcodeReader();
            Result result = reader.Decode((Bitmap)picBox1.Image);
        }
    }
}
